<template>
  <div class="big-box">
    <!--v2tree-->
    <div class="tooltip"></div>
    <div class="tree-box">
      <div class="tree-top" >
        <el-input
            v-model="keyword"
            placeholder="输入关键字查询目录"
            @input="onQueryChanged"
            style="width: 63%"
        />
        <el-button @click="addFileList" style="width: 34%;font-size: 12px;">添加一级目录</el-button>
      </div>
        <el-tree-v2
            :data="fileListData"
            :props="props"
            :height="height"
            class="tree-bot"
            :filter-method="filterMethod"
            ref="fileListRef"
            :indent="10"
            :expand-on-click-node="false"
        >
          <template #default="{ node, data }">
            <span
                class="custom-tree-node"
                @click="getFileLists(node)"
                @mouseenter="showLabels(node,$event,data)"
                @mouseleave="hideLabels(node,$event)"
            >
              <div
                  class="tree-label"
                  :id="node.key"
              >
                {{ data.fileName }}
              </div>
              <div>
              <!--<span class="label-edit"  style="z-index: 999">-->
                <span class="text-link" v-show="node.data.isLinkShow">
                  <a
                      class="file-title-edit"
                      @click="editLabel(node)"
                  >
                    <el-icon color="#3E5ECD">
                      <Edit />
                    </el-icon>
                  </a>
                  <a
                      class="file-title-edit"
                      @click="addSonList(node)"
                  >
                    <el-icon color="#3E5ECD">
                      <Plus />
                    </el-icon>
                  </a>
                  <a
                      class="file-title-edit"
                      @click="deleteLabel(node)"
                  >
                    <el-icon color="#3E5ECD">
                      <Delete/>
                    </el-icon>
                  </a>
                  <a
                      class="file-title-edit"
                      @click="uploadFile(node)"
                  >
                    <el-icon color="#3E5ECD">
                      <Upload />
                    </el-icon>
                  </a>
                </span>
                <!--</span>-->
              </div>
            </span>
          </template>
      </el-tree-v2>
    </div>
    <!--文件表格展示区-->
    <div class="table-box">
      <el-table
          :data="tableData"
          stripe
          border
          class="file-table"
          style="width: 98%;height: 87vh"
          header-align="center"
          :empty-text="fileMsg"
          max-height="87vh"
      >
        <el-table-column
            header-align="center"
            type="index"
            align="center"
            label="序号"
            :index="1"
            width="50%"
        />
        <el-table-column
            header-align="center"
            align="center"
            prop="name"
            label="文件名"
            width="350%"
        />
        <el-table-column
            header-align="center"
            align="center"
            prop="size"
            label="大小"
            width="100%"
        />
        <el-table-column
            header-align="center"
            align="center"
            prop="type"
            label="类型"
            width="100%"
        >
          <template #default="{ row }">
            <el-tag>{{row.type}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            header-align="center"
            prop="uploader"
            label="上传人员"
            width="150%"
            align="center"
        />
        <el-table-column
            header-align="center"
            align="center"
            prop="type"
            label="查看权限等级"
            width="130%"
        >
          <template #default="{ row }">
            <el-tag
                type="success"
            >
              {{row.root}}级
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            header-align="center"
            prop="created_at"
            label="上传时间"
            width="150%"
            align="center"
        >
          <template #default="{ row }">
            {{ upTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column
            header-align="center"
            label="操作"
            align="center"
            min-width="300px"
        >
          <template #default="slot">
            <el-button
                type="primary"
                :icon="Edit"
                @click="editFile(slot.row)"
            />
            <el-button
                type="primary"
                :icon="Search"
                @click="previewFile(slot.row)"
            />
            <el-button
                type="primary"
                :icon="DeleteFilled"
                @click="delFile(slot.row)"
                v-if="editRoot"
            />
            <el-button
                type="primary"
                :icon="Download"
                @click="downLoadFile(slot.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <div class="floder-empty" v-if="isFloderEmpty">
        <el-empty :description="fileMsg"></el-empty>
      </div>
    </div>

    <!--编辑文件名的dialog-->
    <el-dialog
        v-model="editDialogVisible"
        title="输入文件名"
        width="20%"
    >
      <el-form
          :model="editFileForm"
          label-width="5vw"
          :rules="editRules"
          ref="editFileFormRef"
          label-position="left"
      >
        <el-form-item label="文件名" prop="newFileName">
          <el-input v-model="editFileForm.newFileName" type="text" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onEdit(editFileFormRef)">确认修改</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>

  <!--删除dialog-->
  <el-dialog
      v-model="delDialogVisible"
      width="15%"
  >
    <span>此操作无法撤销,确认删除?</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closedelDialog">取消</el-button>
        <el-button type="primary" @click="onDelFile">
          确认删除
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!--  dialogs-->

  <UploadFiles ref="uploadFileRef" @getFileLists="getFileLists" />
  <EditCatalogDialog ref="catalogDialogRef" @reLoadFileList="reLoadFileList"/>
  <!--文件预览-->
  <div class="preview-box" v-if="isPreviewShow" ref="previewRef">
    <iframe  :src="fileUrl" class="preview"></iframe>
    <span class="close" @click="closePreview"><Close /></span>
  </div>


  <!--头部搜索和上传-->
  <div class="upload-box">
    <!--搜索-->
    <div class="search-box">
      <el-input
          v-model="keywordInput"
          placeholder="输入关键字查询文件"
          clearable
          @blur="isEmpty"
          v-on:keydown.enter="onSearch"
      />
      <el-button
          plain
          :icon="Search"
          @click="onSearch"
      >
        搜索
      </el-button>
    </div>

    <UpLoad
        v-if="isUploadShow"
        ref="uploadRef"
    />
  </div>
</template>

<script setup>
import {ElButton, ElIcon, ElInput, ElTable, ElTableColumn, ElEmpty, ElTooltip, ElTreeV2, ElMessage, ElFormItem, ElForm, ElDialog,ElTag, ElLink, ElScrollbar} from "element-plus";
import {Edit, Plus, Delete, Search, Download, DeleteFilled, Upload,} from '@element-plus/icons-vue'
import {Close} from "@element-plus/icons-vue";
import {computed, onMounted, reactive, ref, watch} from "vue";
import EditCatalogDialog from "@/components/FileList/EditCatalogDialog.vue";
import UploadFiles from "@/components/HomePage/UpLoad.vue"
import {useRouter} from "vue-router";
import {getlist, getfiles, updatefile, download, delfile, preview, queryfile} from '@/api/index.js'
import 'viewerjs/dist/viewer.css'
import emitter from "@/lib/eventBus";
import UpLoad from "@/components/HomePage/UpLoad.vue";
import { debounce } from "lodash"
import {isRoot, } from "@/lib/utils"
import axios from "axios"
import {baseurl} from "@/api/http"

const router = useRouter()
// 目录列表
const fileListData = ref([])
// 查询关键字
const keyword = ref('')
// 用来监听查询filter的ref
const fileListRef = ref()
// 文件编辑dialog的ref
const fileDialogRef = ref()
// 目录编辑dialog的ref
const catalogDialogRef = ref()
// 上传文件dialog的ref
const uploadFileRef = ref()
// tree映射参数
const props = {
  value: 'listId',
  label: 'fileName',
  children: 'children',
}
// 文件表格数据
const tableData = ref([])
// 当前选择的文件夹是否为空
const isFloderEmpty = ref(false)
//tree视口高度
let height = ref(0)
// 表格空白时占位文字
let fileMsg = ref('当前文件夹没有文件')
// 当前正在操作的文件夹节点
let currentList = ref([])
// 文件预览url
let images = ref([
  "E:\\workFiles\\Projects\\php\\syhyDocManSys\\syhydocmansystem\\storage\\files/pic\\1b7c033048f1ffc4ccc6ae3a9435bb31695709429.png"
])
let fileUrl = ref('')
let isPreviewShow = ref(false)
const previewRef = ref()
//查询文件的关键字
let keywordInput = ref('')
// uoload dialog的显隐
const uploadRef = ref()
const isUploadShow = ref(true)
//编辑权限
let editRoot = ref()


onMounted(async ()=>{
  try {
    emitter.emit('home_menu','/fileList')
    let obj
    if(!localStorage.getItem('syhyDocManSys')){
      ElMessage({
        message:'请先登录',
        type:'error'
      })
      return router.push('/login')
    } else {
      obj = JSON.parse(localStorage.getItem('syhyDocManSys'))
      const res = await getlist({userId:obj.id})
      fileListData.value = res.data
      // console.log(fileListData.value)
      if(obj.root === 2){
        editRoot.value = false
      } else {
        editRoot.value = true
      }
    }
    getHeight()
    window.addEventListener('resize', () => { //监听浏览器窗口大小改变
      //浏览器变化执行动作
      getHeight()
    })
  } catch (error){
    // console.log(error)
  }
})
// 获取视口高度
const getHeight = ()=>{
  height.value = window.innerHeight * 0.96*0.79
}

/*v2tree*/
const onQueryChanged = (query) => {
  if(fileListRef.value){
    fileListRef.value.filter(query)
  }
}

const filterMethod = (query, node) => {
  if(node.fileName) {
    return node.fileName.includes(query)
  }
}

/*文件夹节点操作函数*/
//鼠标经过节点
const showLabels = (node,data)=>{
  node.data.isLinkShow = true
  const fileName = document.getElementById(node.key)
  if(fileName && fileName.scrollWidth > fileName.offsetWidth){
    const tooltip = document.querySelector('.tooltip')
    // const label = document.querySelector(#)
    tooltip.innerHTML = node.label
    tooltip.style.top = fileName.getBoundingClientRect().top-20+'px'
    tooltip.style.left = fileName.getBoundingClientRect().left+50+'px'
    tooltip.style.display = 'block'
  } else {
    return
  }
}

// debounce(showLabels, 200)

//光标离开节点
const hideLabels = (node)=>{
  node.data.isLinkShow = false
  const tooltip = document.querySelector('.tooltip')
  if(tooltip.style.display === 'block'){
    let label = document.querySelector('.ree-label')
    tooltip.style.display = 'none'
  } else {
    return
  }
}
debounce(hideLabels, 200)

//添加节点
const addSonList = (node)=>{
  catalogDialogRef.value.showAddSonCatalogDialog(node)
}

//编辑节点
const editLabel = (node)=>{
  catalogDialogRef.value.showEditDialog(node)
}

//删除节点
const deleteLabel = (node)=>{
  catalogDialogRef.value.showDelDialog(node.data)
}

// 节点查询
const filterNode = (value, data)=>{
  if (!value) return true
  return data.fileName.includes(value)
}

// 刷新文件夹列表
const reLoadFileList =async ()=>{
  if(!localStorage.getItem('syhyDocManSys')){
    ElMessage({
      message:'请先登录',
      type:'error'
    })
    return router.push('/login')
  } else {
    let obj = JSON.parse(localStorage.getItem('syhyDocManSys'))
    const res = await getlist({userId:obj.id})
    fileListData.value = res.data
    // console.log(res)
    }

}

//获取当前文件夹节点下的文件列表
const getFileLists = async (node)=>{
  if(!localStorage.getItem('syhyDocManSys')){
    ElMessage({
      message:'请先登录!',
      type:'error'
    })
    return router.push('/login')
  }
  let obj = JSON.parse(localStorage.getItem('syhyDocManSys'))
  currentList.value = node
  const {data : res} = await getfiles({
    listId:node.key,
    userId:obj.id
  })
  if(res.code === 201){
    fileMsg.value = res.data
    tableData.value = []
  } else if (res.code === 401) {
    ElMessage({
      message:'文件夹不存在或已被删除',
      type:"warning"
    })
  } else if (res.code === 400) {
    ElMessage({
      message:'获取失败,请重试',
      type:"warning"
    })
  } /*else {
    tableData.value = res.data
  }*/
  else {
    tableData.value = res.data
    // ElMessage({
    //   message:'获取成功!',
    //   type:"success"
    // })
  }
}

// 添加一级目录
const addFileList = ()=>{
  catalogDialogRef.value.showAddFirstCatalogDialog()
}

//在文件夹上传文件
const uploadFile = (node,)=>{
  uploadFileRef.value.showDialog(node) //使用子组件的函数需要子组件中使用defineExpose暴露
}

/*文档操作*/

/*编辑文档名称*/
// 当前正在编辑的row
let currentRow = reactive({})

//文档数据
const editDialogVisible = ref(false)
// 表单的ref
const editFileFormRef = ref(false)
const editFileForm = reactive({
  newFileName:''
})
// 校验规则
const editRules = {
  newFileName:[
    { required: true, message: '文件名不能为空', trigger: 'blur' },
  ]
}
// 显示文档编辑dialog
const editFile = (row)=>{
  editDialogVisible.value = true
  currentRow = row
}

// 提交修改文件名表单
const onEdit = async (formRef)=>{
  if(!localStorage.getItem('syhyDocManSys')){
    ElMessage({
      message:'请先登录',
      type:'error'
    })
    return router.push('/login')
  }
  let o = JSON.parse(localStorage.getItem('syhyDocManSys'))
  if(currentRow.name === editFileForm.newFileName){
    ElMessage({
      message:'修改后的名称不能与原文件名一致!',
      type:'error'
    })
    return
  }
  const info = {
    fileId:currentRow.id,
    newFileName:editFileForm.newFileName,
    userId:o.id
  }

  try {
    const v = await formRef.validate()
    if(v){
      const {data:res} = await updatefile(info)
      console.log(res)
      if(res.code === 200){
        ElMessage({
          message:'修改成功!',
          type:'success'
        })
        editDialogVisible.value = false
        editFileForm.newFileName = ''
        getFileLists({key:currentList.value.key})
      }
    } else {

    }
  } catch (error){
    ElMessage({
      message:error,
      type:'warning'
    })
  }
}

const closeDialog = ()=>{
  editDialogVisible.value = false
}


/*删除文档操作*/
const delDialogVisible = ref(false)
let obj
// 显示文档删除dialog
const delFile = (row)=>{
  delDialogVisible.value = true
  currentRow = row
  // console.log(currentRow.id)
}
//删除文件
const onDelFile = async ()=>{
  try {
    if(!localStorage.getItem('syhyDocManSys')){
      ElMessage({
        message:'请先登录',
        type:'error'
      })
      return router.push('/login')
    }
    obj = JSON.parse(localStorage.getItem('syhyDocManSys'))
    const {data:res} = await delfile({fileId:currentRow.id,userId:obj.id})
    // const data = await delfile({fileId:currentRow.id,userId:obj.id})
    // console.log(data)
    if(res.code === 200){
      delDialogVisible.value = false
      getFileLists({key:currentList.value.key})
      ElMessage({
        message:'删除成功!',
        type:'success'
      })
    }
  } catch (e) {
    console.log(e)
  }
}

const closedelDialog = () => {
  delDialogVisible.value = false
}

// 文档预览
const previewFile = async (row)=>{
  currentRow = row
  // console.log(row)
  // fileUrl.value = `http://www.lv8.com:8000/preview?fileId=${currentRow.id}`
  // fileUrl.value = `http://192.168.10.100:8000/preview?fileId=${currentRow.id}`
  fileUrl.value = `${baseurl}/preview?fileId=${currentRow.id}`
  isPreviewShow.value = true
}

//关闭预览
const closePreview = ()=>{
  isPreviewShow.value = false
}

/*文档下载*/
const downLoadFile = async (row)=>{
  const u = JSON.parse(localStorage.getItem('syhyDocManSys'))
  //保存当前行信息
  currentRow = row
  // console.log(row)
  try {
    const response = await download({fileId:row.id,userId:u.id}); // 替换为实际的文件ID
    console.log(response)
    // console.log(response)
    const blob = new Blob([response.data],{ type:row.type === 'zip' ? 'application/zip,charset=utf-8' : 'application/x-rar-compressed,charset=utf-8' });
    const filename = row.name+'.'+row.type // 获取文件名

    // // 创建一个临时链接元素来触发下载
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    ElMessage({
      message:'文件不存在,请刷新后重试',
      type:'warning'
    })
  }
}



//文档查询获取到数据
const getQueryInfo = ()=>{
  emitter.on('getQueryInfo',(queryFileList)=>{
    tableData.value = queryFileList
    // console.log(queryFileList)
  })
}

//判断当前是否查询
const isQuery = ()=>{
  emitter.on('empty',(b)=>{
    if(!b && !currentList.value){
      tableData.value = []
    } else if (!b && currentList.value){
      getFileLists({key:currentList.value})
    } else {
      // console.log('mitt')
    }
  })
}


/*关键字查询文档*/
const showUpLoad = ()=>{
  uploadRef.value.isDialogShow = true
}

//失去焦点时判断input是否为空
const isEmpty = ()=>{
  if(!keywordInput.value){
    tableData.value = []
  }
}

// 查询
const onSearch = async ()=>{
  tableData.value = []
  if(!keywordInput.value){
    ElMessage({
      message:'请输入关键字',
      type:'warning'
    })
    return
  }
  try {
    const {data:res} = await queryfile({keyword:keywordInput.value})
    console.log(res)
    if(res.code === 200){
      tableData.value = res.data.data
    } else if(res.code === 401){
      ElMessage({
        message:'没有符合条件的文件',
        type:'warning'
      })
    } else {
      ElMessage({
        message:'请输入正确关键字!',
        type:'error'
      })
    }
  } catch (e) {
    // console.log(e.message)
    ElMessage({
      message:'未知错误!',
      type:'error'
    })
    // location.reload()
  }
}


// 计算属性返回上传时间
const upTime = computed(()=>{
  return (dateString) => {
    // 剪裁上传时间字符串为日期格式
    const date = new Date(dateString);
    return date.toLocaleDateString("zh-CN");
  }
})


</script>

<style scoped lang="less">
.tree-box{
  width: 18%;
  height: 96%;
  margin-top: 1%;
  margin-left: 1%;
  border-radius: 1.5vh;
  background-color: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
  .tree-top{
    padding-right: 0.5vw;
    padding-left: 0.5vw;
    display: flex;
    padding-top: 6%;
    justify-content: space-between;
    .search{
      margin-top: 1%;
      margin-bottom: 3%;
      .el-input{
        width: 70%;
        margin-right: 4%;
      }
    }
    .btn-list{
      display: flex;
      justify-content: space-evenly;
      width: 70%;
      padding-left: 13%;
    }
  }
  .tree-bot{
    padding-left: 1vw;
    padding-top: 2vh;
    /deep/.el-tree__empty-block {
      width: 85%;
    }
    .custom-tree-node{
      width: 15vw;
      text-align: left;
      .tree-label{
        width: 60%;
        overflow: hidden;//溢出隐藏
        white-space: nowrap;//禁止换行
        text-overflow: ellipsis;//...
      }
      .text-link{
        .file-title-edit{
          margin-right: .5vw;
          z-index: 999;
        }
      }
      &:hover{
        cursor: pointer !important;
      }
      &:hover{
        display: flex;
        margin-right: 1vw;
      }
    }
  }
}

.table-box{
  height: 90%;
  width: 79%;
  background-color: white;
  border-radius: 1.2vh;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
  margin-top: 3%;
  margin-left: 1%;
  padding-top: 1%;
  .file-table{
    margin: 0 auto;
  }
  /deep/.el-empty{
    padding-top: 14%;
  }
}
.big-box{
  display: flex;
  height: 100%;
}

.preview{
  position: absolute;
  top: 3vh;
  left: 7vw;
  width: 80vw;
  height: 85vh;
  background-color: #F5F5F5;
  z-index: 999;
  border-radius: 5px;
  border: 1px solid darkgray;
}
.close{
  position: absolute;
  top: 4vh;
  left: 85.8vw;
  height: 2.5vh;
  width: 2.5vh;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 999;
  font-size: 1.5vh;
  font-weight: 800;
  color: gray;
  cursor: pointer !important;
}
.upload-box{
  z-index: 99;
  position: absolute;
  top: 1%;
  left: 26%;
  height: 7%;
  width: 74%;
  background-color: transparent;
  .search-box{
    position: absolute;
    top: 4%;
    left: 65%;
    width: 33%;
    display: flex;
    .el-input{
      margin-right: 1vw;
    }
  }
}
/deep/.el-table__row.el-table__row--striped  {
  //background-color: #C1FFC1 !important;
  background-color: red !important;
}
.tooltip{
  display: none;
  position: absolute;
  //top: 100%;
  //left: 0;
  background-color: white;
  padding: 5px;
  border: 1px solid #ccc;
  box-shadow: 0 2px 4px rgba(0,0,0,.1);
  border-radius: 5px;
  width: auto;
  overflow: auto;
  z-index: 999;
}
</style>
